<template>
	<view class="">
		<!-- <u-navbar title="声音设置" leftIconColor="#fff" :placeholder="true" :bgColor="bgColor"
			:titleStyle="titleStyle" :autoBack="true" ></u-navbar> -->
		<headerinfo></headerinfo>

		<image src="/static/images/backimg.png" mode="widthFix" class="backImg" @click="back"></image>
		<view class="noticelist">
			<view class="li">
				时长推荐 3~10秒;
			</view>
			<view class="li">
				推荐数据集中(人话:不要太多留白，留白对AI来说是废数据);
			</view>
			<view class="li">
				不要有噪音，除了你要需要的那个声音，其他的所有声音都是噪音;
			</view>
			<view class="li">
				吐字清晰，一个字一个字的咬准喽，不要连音;
			</view>
			<view class="li" style="font-weight: bold;">
				音频使用普通话，不要用方言;
			</view>

			<view class="tablist">
				<span :class="inv == 0?'act':''" @click="inv = 0">自己上传音频文件</span>
				<span :class="inv == 1?'act':''" @click="inv = 1">使用录音</span>
			</view>
			<view class="form" v-if="inv == 0">
				<view class="title">
					<input type="text" placeholder="请输入音频对应的文本" v-model="usertext" />
				</view>
			</view>
			<view class="form" v-if="inv == 1">
				<view class="title">
					请在以下古诗中选择一条录音
				</view>


				<!-- <view class="list" @click="gushidia = true">
					{{gushi?gushi:'请选择古诗'}} <i class="iconfont">&#xe606;</i>
				</view> -->

				<el-select v-model="gushi" placeholder="请选择古诗" style="width: 100%;">
					<el-option v-for="item in gushilist" :key="item.name" :label="item.name" :value="item.name">
					</el-option>
				</el-select>


				<button id="startBtn" @click="startRecording" :style="startBtnStyle" v-show="!isRecording">
					开始录音
				</button>

				<button id="stopBtn" @click="stopRecording" :style="stopBtnStyle" v-show="isRecording">
					停止录音
				</button>

			</view>

			<view class="uplist" v-if="inv == 0">
				<view class="list" style="display: flex;justify-content: space-between;">
					<span>上传音频文件

						<el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false"
							:on-change="handlePreview">
							<div class="uploadtext">上传</div>
						</el-upload>

					</span>


					<span style="width: 50%;margin-left: 30rpx;" @click="jiance">检测声音文字</span>
				</view>
			</view>


			<view class="uplist" v-if="inv == 0" @click="tijiao" style="width: 100%;margin: 30rpx auto;">
				<view class="list">
					<span>提交</span>
				</view>
			</view>
		</view>


	


	</view>
</template>

<script>
	import minxins from '../../common/upload.js';
	// import soundRecording from '@/components/sound-recording/sound-recording.vue'
	import headerinfo from '@/components/headerinfo'
	export default {
		mixins: [minxins],
		components: {
			headerinfo
		},
		data() {
			return {
				luyingdia: false,
				familyMemberId: '',
				bgColor: '#de4849',
				titleStyle: {
					color: '#fff'
				},
				selectdefaultProps: {
					label: "name",
					value: "id"
				},
				gushidia: false,
				gushilist: [],
				gushi: '',
				recorderManager: null,
				isRecording: false,
				inv: 0,
				usertext: '',
				uploadvideo: '',
				isRecording: false,
				showDownload: false,
				statusText: '点击下方按钮开始录音',
				mediaRecorder: null,
				audioChunks: [],
				audioBlob: null,
				mediaStream: null,
				// 按钮样式
				startBtnStyle: {
					backgroundColor: '#4CAF50',
					color: 'white'
				},
				stopBtnStyle: {
					backgroundColor: '#f44336',
					color: 'white'
				},
				downloadBtnStyle: {
					backgroundColor: '#2196F3',
					color: 'white'
				}
			};
		},
		onLoad(e) {
			if (e.familyMemberId) {
				this.familyMemberId = e.familyMemberId
			}
		},
		onShow() {
			this.getgushi()
		},
		mounted() {
			this.recorderManager = uni.getRecorderManager();
		},
		beforeUnmount() {
			// 组件卸载前清理资源
			if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
				this.mediaRecorder.stop();
			}
			if (this.mediaStream) {
				this.mediaStream.getTracks().forEach(track => track.stop());
			}
		},
		methods: {
			getgushi() {
				this.$api.getReadText().then(res => {
					console.log(res)

					var arr = [];
					for (var key in res) {
						arr.push({
							name: res[key],
							id: res[key]
						});
					}

					this.gushilist = arr

				})
			},
			langchecked(e) {
				this.gushi = e.value
			},
			jiance() {
				let zhuanhuan = {
					soundFile: this.uploadvideo,
					familyMemberId: this.familyMemberId
				}
				this.$api.soundToText(zhuanhuan).then(res => {
					this.usertext = res.soundText
				})
			},
			tijiao() {
				let data = {
					familyMemberId: this.familyMemberId,
					soundFile: this.uploadvideo,
					soundText: this.usertext
				}
				this.$api.uploadFamilyMemberSound(data).then(res => {
					this.$Show.successJump('设置成功')
					
					setTimeout(()=>{
						uni.navigateBack()
					},1500)
				})

			},
			handlePreview(file) {

				console.log(file)
				const tempFilePaths = URL.createObjectURL(file.raw);

				// 限制 300K
				var fileName = Date.now() + '_' + Math.round(Math.random() *
					100000000) + '.' + file.name + '.wav'


				var familyId = uni.getStorageSync('familyId') ? uni
					.getStorageSync('familyId')[0] : ''

				this.uploadUserImage(tempFilePaths, 'image', fileName, familyId, (
					imgUrl) => {

					this.uploadvideo = imgUrl
					
					this.jiance()

				})
			},
			uploadVideo() {

				// if (!this.usertext) {
				// 	return this.$Show.show('请填写音频文件对应的文本')
				// }


				uni.chooseMessageFile({
					count: 1, //选取的文件个数限制
					type: 'file',
					success: (res) => {
						// 获取到了音频文件
						const tempFilePaths = res.tempFiles[0].path;
						console.log(res)

						// 限制 300K
						var fileName = Date.now() + '_' + Math.round(Math.random() *
							100000000) + '.' + tempFilePaths.substring(tempFilePaths.lastIndexOf(
							'.') + 1)

						var familyId = uni.getStorageSync('familyId') ? uni
							.getStorageSync('familyId')[0] : ''

						this.uploadUserImage(tempFilePaths, 'image', fileName, familyId, (
							imgUrl) => {

							this.uploadvideo = imgUrl

						})
					}

				})

			},
			startluying() {

				if (!this.gushi) {
					return this.$Show.show('请选择上述古诗')
				}

				this.luyingdia = true

				// this.recorderManager.start({
				// 	duration: 10000, // 录音的最大时长，单位 ms，这里设置为60秒
				// 	sampleRate: 44100, // 采样率
				// 	numberOfChannels: 1, // 录音的声道数
				// 	encodeBitRate: 192000, // 编码码率
				// 	format: 'm4a' // 音频格式
				// });


				// this.isRecording = true;
				// this.recorderManager.onStart(() => {
				// 	console.log('录音开始');
				// });
				// this.recorderManager.onError((err) => {
				// 	console.error('录音错误：', err);
				// });
			},
			
			async startRecording() {

				if (!this.gushi) {
					return this.$message.error('请选择古诗')
				}
				try {
					// 请求麦克风权限
					this.mediaStream = await navigator.mediaDevices.getUserMedia({
						audio: {
							sampleRate: 44100, // 设置采样率
							channelCount: 1 // 单声道
						}
					});

					// 创建MediaRecorder实例
					this.mediaRecorder = new MediaRecorder(this.mediaStream);

					// 设置数据处理器
					this.mediaRecorder.ondataavailable = (event) => {
						this.audioChunks.push(event.data);
					};

					// 录音停止处理
					this.mediaRecorder.onstop = () => {
						this.audioBlob = new Blob(this.audioChunks, {
							type: 'audio/wav' // 明确指定WAV格式
						});
						this.audioChunks = [];
						this.showDownload = true;
						this.statusText = '录音已保存，可以下载';
					};

					// 开始录音
					this.mediaRecorder.start();
					this.isRecording = true;
					this.statusText = '正在录音...';

				} catch (err) {
					this.statusText = '无法访问麦克风，请检查权限设置';
					console.error('录音错误:', err);
				}
			},

			stopRecording() {
				if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
					this.mediaRecorder.stop();
					this.isRecording = false;
					this.statusText = '录音已停止';
					// 停止所有媒体轨道
					this.mediaStream.getTracks().forEach(track => track.stop());
				}

				setTimeout(() => {
					uni.showLoading({
						title:'上传中...'
					})
					if (this.audioBlob) {

						const tempFilePaths = URL.createObjectURL(this.audioBlob);

						// 限制 300K
						var fileName = Date.now() + '_' + Math.round(Math.random() *
							100000000) + '.' + 'music.wav'
						
						var familyId = uni.getStorageSync('familyId') ? uni
							.getStorageSync('familyId')[0] : ''
						
						this.uploadUserImage(tempFilePaths, 'image', fileName, familyId, (
							imgUrl) => {
						
							let data = {
								familyMemberId: this.familyMemberId,
								soundFile: imgUrl,
								soundText: this.gushi
							}
							this.$api.uploadFamilyMemberSound(data).then(res => {
								uni.hideLoading()
								this.$Show.successJump('设置成功')
								// setTimeout(()=>{
								// 	uni.navigateBack()
								// },1500)
							})
						
						})
						

					}
				}, 500)

			},

			back() {
				uni.navigateBack()
			}

		}
	};
</script>

<style lang="scss">
	.noticelist {
		padding: 30rpx;
		width: 50%;
		margin: 0 auto;
		box-shadow: 0 0 3px #ccc;
		border-radius: 20rpx;
		margin-top: 30rpx;

		.li {
			margin-bottom: 40rpx;
			font-size: 32rpx;
		}
	}

	.form {
		.title {
			margin-bottom: 20rpx;
			font-size: 30rpx;

			input {
				border: 1px solid #ccc;
				border-radius: 20rpx;
				height: 110rpx;
				line-height: 110rpx;
				padding: 0 20rpx;
			}
		}

		.list {
			width: 100%;
			border: 1px solid #cccbcb;
			padding: 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-radius: 10rpx;
			font-size: 32rpx;

			.iconfont {
				margin-left: 30rpx;
			}
		}
	}

	.tablist {
		display: flex;
		align-items: center;
		height: 100rpx;
		margin-bottom: 30rpx;

		span {
			height: 100rpx;
			border-bottom: 1px solid #fff;
			width: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
		}

		.act {
			border-color: #de4849;
			color: #de4849;
		}
	}

	.uplist {
		display: flex;
		align-items: center;
		margin-top: 60rpx;

		.list {
			width: 100%;

			span {
				width: 100%;
				height: 100rpx;
				display: flex;
				align-items: center;
				border-radius: 20rpx;
				background-color: #de4849;
				color: #fff;
				justify-content: center;
				font-size: 32rpx;
				position: relative;

				.uploadtext {
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					z-index: 100;
					background-color: red;
					opacity: 0;
				}

			}
		}
	}

	.container {
		margin-top: 50px;
		text-align: center;
		max-width: 800px;
		margin: 0 auto;
		padding: 20px;
	}

	button {
		padding: 5px 20px;
		font-size: 16px;
		cursor: pointer;
		margin: 10px;
		border: none;
		border-radius: 5px;
		min-width: 120px;
	}

	#status {
		margin: 20px 0;
		font-weight: bold;
		min-height: 24px;
	}

	.backImg {
		width: 60rpx;
		cursor: pointer;
		height: auto;
		margin: 15rpx 25%;
	}
</style>